<template>
  <a-modal v-model="modelVisible" title="预览" :destroyOnClose="true" :footer="null" @cancel="$emit('close')" :width="900">
    <a-spin :spinning="spinning">
      <div class="ql-editor-wrapper" style="min-height: 500px">
        <div class="ql-editor-content ql-editor-content2">
          <div class="editor-main editor-main2">
            <div class="sealnew-name" :style="{ width: `${a4_width}px` }">
              <div class="left" style="flex: 1">{{ name }}.pdf</div>
              <div style="width: 160px; flex-shrink: 0; text-align: right">
                <a-button style="width: 32px; padding: 0; margin-right: 10px" @click="pageUp">
                  <a-icon type="left" />
                </a-button>
                {{ pageCount > 0 ? currentPage : 0 }}/{{ pageCount || 0 }}
                <a-button style="width: 32px; padding: 0; margin-left: 10px" @click="pageDown">
                  <a-icon type="right" />
                </a-button>
              </div>
            </div>
            <div
              :style="{
                width: `${a4_width}px`,
                position: 'relative',
                margin: '0 auto',
                boxShadow: '0px 2px 16px 0px rgba(0, 0, 0, 0.1)'
              }"
            >
              <pdf
                v-if="src"
                ref="pdf"
                :src="src"
                :page="currentPage"
                @num-pages="pageCount = $event"
                @page-loaded="currentPage = $event"
                @error="pdfError"
              />
              <template v-for="item in dropList">
                <vue-draggable-resizable
                  :draggable="false"
                  v-if="item.page === currentPage"
                  :ref="`${item.type}${item.id}`"
                  :key="item.id"
                  :parent="true"
                  :resizable="false"
                  :w="seal_size"
                  :h="item.type === 'seal' ? seal_size : 50"
                  :x="item.x"
                  :y="item.y"
                  class-name="editor-main-drag"
                >
                  <!-- <div class="editor-main-drag-close">
                  <a-popconfirm title="确认要删除合同内的这个印章吗？" ok-text="确认" cancel-text="取消" @confirm="remove(item.id)">
                    <a-icon type="close-circle" />
                  </a-popconfirm>
                </div> -->
                  <div v-if="item.type === 'seal'">
                    <img src="@/assets/img/seal-circle.png" alt="" />
                    <!-- <div class="editor-main-drag-sign">企业签署日期</div> -->
                  </div>
                  <div v-if="item.type === 'sign'">
                    <div class="editor-main-drag-sign">电子签名</div>
                    <!-- <div class="editor-main-drag-sign">个人签署日期</div> -->
                  </div>
                  <div v-if="item.type === 'holder'">
                    <div class="editor-main-drag-sign lp">法人章</div>
                    <!-- <div class="editor-main-drag-sign">个人签署日期</div> -->
                  </div>
                  <!-- <img v-if="item.type === 'seal'" src="@/assets/img/seal-circle.png" alt="">
              <div v-if="item.type === 'seal_date'" class="editor-main-drag-sign">企业签署日期</div>
              <div v-if="item.type === 'sign'" class="editor-main-drag-sign">电子签名</div>
              <div v-if="item.type === 'sign_date'" class="editor-main-drag-sign">个人签署日期</div> -->
                </vue-draggable-resizable>
              </template>
            </div>
          </div>
        </div>
      </div>
    </a-spin>
  </a-modal>
</template>
<script>
// 设定 A4 尺寸为 795 * 1125，印章大小为 159 * 159
const A4_WIDTH = 816;
const A4_HEIGHT = 1156;
const SEAL_SIZE = 159;
const FIX_SEAL_SIZE = 40;
const HALF_SEAL_SIZE = 80;
const HALF_SEAL_SIZE_ARR = [0, 80, 80, 50];
const FIX_SEAL_SIZE_ARR = [0, 40, 110, 80];
import {
  templateDetailReq,
  templateSealListAllReq,
  templateSealCreateReq,
  templateSealDeleteReq,
  postSaveOrUpdate
} from "@/api/company/contract";
import { getToken } from "xqjr-module-auth";
import pdf from "vue-pdf";
import CMapReaderFactory from "vue-pdf/src/CMapReaderFactory.js";
import VueDraggableResizable from "vue-draggable-resizable";
import axios from "axios";
import { isContainByString } from "@/utils/index";
let uuid = 90000000;
export default {
  components: {
    pdf,
    VueDraggableResizable
  },
  inject: ["reload"],
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    templateId: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      modelVisible: false,
      spinning: true,
      isContainByString,
      src: null,
      currentPage: 1,
      pageCount: 0,
      loading: false,
      categoryId: null,
      name: "",
      content: "",
      // dragList: ['seal', 'seal_date', 'sign', 'sign_date'],
      dragList: ["seal", "sign", "holder"],
      dropList: [],
      oldSealIdList: [],
      a4_width: A4_WIDTH,
      a4_height: A4_HEIGHT,
      seal_size: SEAL_SIZE,
      seal: [],
      sign: [],
      sealJson: {},
      signJson: {}
    };
  },
  watch: {
    visible(v) {
      this.modelVisible = v;
      if (v) {
        this.spinning = true;
        this.$nextTick(() => {
          this.loadTemplate();
        });
      } else {
        this.src = null;
        this.dropList = [];
        this.currentPage = 1;
        this.pageCount = 0;
      }
    },
    pageCount(val) {
      if ((!!val || val === 0) && !this.loading) {
        this.loadTemplateSeals();
      }
    }
  },
  methods: {
    pdfError(err) {
      console.log("Error", err);
    },
    loadTemplate() {
      templateDetailReq(this.templateId, this.$route.meta.pageType)
        .then((res) => {
          this.categoryId = res.data.categoryId;
          this.name = res.data.name;
          this.content = res.data.content;
          this.$nextTick(() => {
            this.loadTemplatePdf();
          });
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    loadTemplatePdf() {
      axios({
        url: "/contract/api/v1/templates/preview",
        method: "post",
        responseType: "blob",
        headers: {
          token: getToken()
        },
        data: {
          fileName: this.name,
          content: this.content
        }
      })
        .then(async (res) => {
          if (URL && URL.createObjectURL) {
            const urlObj = URL.createObjectURL(new Blob([res.data], { type: "application/pdf" }));
            this.src = pdf.createLoadingTask({ url: urlObj, CMapReaderFactory });
          }
          // this.reload();
          // if (this.src.docId !== "d0") {
          //   this.reload();
          //   return;
          // }
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    loadTemplateSeals() {
      this.loading = true;
      templateSealListAllReq(this.templateId, this.$route.meta.pageType)
        .then((res) => {
          this.dropList = res.data.map((item) => ({
            id: item.id,
            page: item.sealPage > this.pageCount ? this.pageCount : item.sealPage,
            x: (item.sealPositionX / 612) * this.a4_width - HALF_SEAL_SIZE_ARR[item.accountType],
            y: this.a4_height - FIX_SEAL_SIZE_ARR[item.accountType] - (item.sealPositionY / 792) * this.a4_height,
            type: this.transType(item.accountType, item.type)
          }));
          this.oldSealIdList = this.dropList.map((item) => item.id);
          this.loading = false;
          setTimeout(() => {
            this.spinning = false;
          }, 500);
        })
        .catch((err) => {
          console.log("debug log --> ", err);
        });
    },
    transType(aType, type) {
      if (aType === 1) {
        return type === 1 ? "sign" : "sign_date";
      } else if (aType === 2) {
        return type === 1 ? "seal" : "seal_date";
      } else if (aType === 3) {
        return "holder";
      } else {
        return "";
      }
    },
    async createTemplateSeal(data) {
      // const res = await templateSealCreateReq(data);
      const res = await postSaveOrUpdate(data, this.templateId, this.$route.meta.pageType);
    },
    async deleteTemplateSeal(ids) {
      const res = await templateSealDeleteReq(ids);
    },
    back() {
      this.$router.back();
    },
    save() {
      var arr = [];
      for (let i = 0; i < this.dropList.length; i++) {
        const accountType = { seal: 2, seal_date: 2, sign: 1, sign_date: 1, holder: 3 }[this.dropList[i]["type"]];
        arr.push({
          accountType: accountType,
          sealPage: this.dropList[i]["page"],
          sealPositionX: ((this.dropList[i]["x"] + HALF_SEAL_SIZE_ARR[accountType]) / this.a4_width) * 612,
          sealPositionY: ((this.a4_height - FIX_SEAL_SIZE_ARR[accountType] - this.dropList[i]["y"]) / this.a4_height) * 792,
          type: { seal: 1, seal_date: 2, sign: 1, sign_date: 2, holder: 1 }[this.dropList[i]["type"]],
          templateId: this.templateId
        });

        // if (this.oldSealIdList.includes(this.dropList[i]["id"])) {
        //   const idx = this.oldSealIdList.findIndex(item => item === this.dropList[i]["id"]);
        //   this.oldSealIdList.splice(idx, 1);
        // }
      }
      this.createTemplateSeal(arr);
      // if (this.oldSealIdList.length > 0) {
      //   // 删除不存在的印章位置
      //   this.deleteTemplateSeal(this.oldSealIdList);
      // }
      // // this.$router.push('/contract/type')
      // // 修改为跳转合同类型设置-合同模板页面
      this.$router.push({
        path: `/${this.isContainByString("contractAdmin") ? "contractAdmin" : "contract"}/setting`,
        query: { id: this.categoryId, current: "2", currentSetting: "1" }
      });
    },
    onDrag(args, id) {
      const index = this.dropList.findIndex((item) => item.id === id);
      this.dropList[index] = Object.assign(this.dropList[index], {
        x: args[0],
        y: args[1]
      });
    },
    add(type) {
      // if (this.dropList.filter(item => item.type === type).length > 0) {
      //   return;
      // }
      this.dropList.push({
        id: 1 + uuid,
        type: type,
        page: 0 + this.currentPage,
        x: this.dropList.length * 20,
        y: this.dropList.length * 20
      });
      uuid++;
    },
    remove(id) {
      const index = this.dropList.findIndex((item) => item.id === id);
      this.dropList.splice(index, 1);
    },
    pageUp() {
      if (this.currentPage > 1) {
        this.currentPage--;
      }
    },
    pageDown() {
      if (this.currentPage < this.pageCount) {
        this.currentPage++;
      }
    },
    jump(i) {
      this.currentPage = parseInt(i);
    }
  }
};
</script>
<style lang="scss" scoped>
.ql-editor-content2 {
  .editor-main2 {
    width: 75%;
    margin: 0;
    overflow: visible;
  }
  .sealnew-name {
    min-height: 32px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 0 auto;
    margin-bottom: 12px;
    .left {
      font-size: 16px;
      font-weight: 500;
      color: rgba(0, 0, 0, 0.85);
    }
  }
  .editor-config2 {
    border-left: 0;
    width: 26%;
  }
}
.editor-tit {
  margin-top: 16px;
  font-size: 12px;
  color: #d2d2d2;
  span {
    color: var(--primary);
  }
}
.editor-tags {
  width: 180px;
  margin-top: 12px;
  display: flex;
  justify-content: space-between;
  .editor-tags-item {
    width: 75px;
    height: 22px;
    background: #f4f4f4;
    border-radius: 2px;
    border: 1px solid #e8e8e8;
    font-size: 12px;
    font-weight: 400;
    color: #595959;
    text-align: center;
    cursor: pointer;
  }
}
</style>
